﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebNext.Domain.Interfaces;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using System.Configuration;

namespace WebNext.DataAccess.Infrastructure
{
	public class NHibernateContextProvider : IDatabaseContextProvider
	{
		private ISessionFactory sessionFactory;
		
		public NHibernateContextProvider()
		{
			string connectionString = ConfigurationManager.AppSettings["SQLSERVER_CONNECTION_STRING"];
			this.sessionFactory = Fluently.Configure()
						.Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString).ShowSql())
						.Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateContextProvider>())
						.BuildSessionFactory();
		}

		public IDatabaseContext CreateContext(UserNameHandler handler)
		{
			string userName = handler();
			return new NHibernateContext(this.sessionFactory.OpenSession(new NHibernateEntityInterceptor(userName)));
		}
	}
}
